<?php

namespace App\Models\Shop;

use App\Helpers\SelfEncrypt;
use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;

class OrderGoodsModel extends BaseModel
{
    protected $table = 'shop_order_goods';

    protected $primaryKey = 'id';

    public $dateFormat = 'U';

    public function createOrderGoods($order_id,array $goods,$specs,$number=1,$zone=1,$buy_type=0,$goods_price,$shop_discount=10)
    {

        $info = new self();
        $info->sub_order_sn = SelfEncrypt::createCode('G');
        $info->order_id = $order_id;
        $info->goods_id = $goods['goods_id'];
        $info->goods_name = $goods['goods_name'];
        $info->goods_spec = $specs;
        $info->goods_img = str2arr($goods['goods_images'])[0];
        $info->price = $goods_price;
        $info->pay_money = $goods_price * $number;
        $info->xf_points_ratio =0;
        $info->pay_xf_points = $shop_discount;
        $info->number = $number;
        $info->goods_zone = $zone;

        return $info->save();
    }

    public function incrementSales($order_id)
    {
        $goods  = self::where('order_id',$order_id)->select(['goods_id','number','goods_spec','pay_money','goods_zone','pay_xf_points'])->get()->toArray();
        if(!$goods){
            return false;
        }
        $shopStats = new ShopStatsModel();
        foreach ($goods as $item) {
            if($item['goods_spec']){
                ShopGoodsSpecValueModel::where('goods_id',$item['goods_id'])->where('goods_spec_items',$item['goods_spec'])->update([
                    'fact_sales_volume'=>DB::raw('`fact_sales_volume`+'.$item['number']),
                    'show_sales_volume'=>DB::raw('`show_sales_volume`+'.$item['number']),
                    'stock'=>DB::raw('`stock`-'.$item['number']),
                ]);
            }else{
                ShopGoodsModel::where('goods_id',$item['goods_id'])->update([
                    'fact_sales_volume'=>DB::raw('`fact_sales_volume`+'.$item['number']),
                    'show_sales_volume'=>DB::raw('`show_sales_volume`+'.$item['number']),
                    'stock'=>DB::raw('`stock`-'.$item['number']),
                ]);
            }
            $shopStats ->addShopStats(0,$item['number'],$item['number'],1,($item['pay_money']* $item['pay_xf_points'] * 0.1),$item['goods_zone']) ;

        }
        return true;
    }
}
